<template>
    <el-dialog title="用户授权" :visible.sync="dialog" width="40%" center @close="closeHandler">
        <el-table :data="tableData" ref="multipleTable" style="width: 100%;margin-bottom: 20px;" 
        v-loading="loading" default-expand-all row-key="menuId" border max-height="600px" :tree-props="{children: 'children', hasChildren: 'hasChildrens'}"
         @select="selectHandler" @select-all="selectAll">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="menuName" label="名称" sortable width="200">
            </el-table-column>
            <el-table-column prop="menuUrl" label="地址" sortable width="230">
            </el-table-column>
            <el-table-column prop="menuIcon" label="图标">
            </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
            <el-button @click="closeHandler">取 消</el-button>
            <el-button type="primary" @click="saveHandler">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import {adminAuthMenusUrl,adminMenusSave,replaceUrlParam} from "@/utils/common"

export default {
  props: {
    dialog: {
      type: Boolean,
      default: false
    },
    auUserId: {
      type: Number,
      default: -1
    }
  },
  watch: {
    auUserId() {
      this.userId = this.auUserId;
      if(this.userId != -1) {
        this.loadMenus();
      }
    }
  },
  data() {
    return {
      tableData: [],
      userId: null,
      loading: false
    };
  },
  mounted() {
    this.loadMenus()
  },
  methods: {
    /**
     * 加载当前登录用户的最大权限
     */
    loadMenus() {
      this.loading = true;
      var user = JSON.parse(sessionStorage.getItem("user"));
      this.axios
        .post(replaceUrlParam(adminAuthMenusUrl,[user.id,this.userId]))
        .then(response => {
          if (response.data.status == "SUCCESS") {
            this.tableData = response.data.data;
            // console.log("menus - ", JSON.stringify(this.tableData));
            this.openHandler();
          } else {
            this.$message.success("菜单列表获取失败");
          }
        })
        .catch(response => {
          console.log("response -   " + response);
        });
    },

    //全选
    selectAll(selection){
        // console.log("12qw",selection)
        this.$refs.multipleTable.clearSelection();
        //查看第一条是否选中来判断是全选还是取消全选
        if(this.isSelectCurrentRow(this.tableData[0], selection)){
            //全选
            this.selectChil(true, this.tableData);
        }
    },
    /**
     * 选择checkbox
     */
    selectHandler: function(selection, row) {
    //   console.log("selection - ", selection, row);
        
      // 将当前元素的子元素设置为选中元素
      this.selectChil(this.isSelectCurrentRow(row, selection),row.children);
      // 将当前元素的父元素设置为选中元素
      this.selectParent(row, selection);
    //   var parentRow = this.findAllParent(row, selection);
    //   console.log(parentRow)
    //   if (parentRow != undefined && this.isSelectOne(parentRow.children, selection)) {
    //     this.$refs.multipleTable.toggleRowSelection(parentRow, true);
    //   } else {
    //     this.$refs.multipleTable.toggleRowSelection(parentRow, false);
    //   }

    // console.log("selection - 111", this.$refs.multipleTable.selection, row);
    },
    //选中/取消当前元素的子元素
    selectChil(isSelect, menuList){
        for (let index = 0; index < menuList.length; index++) {
            var menu = menuList[index];
            this.$refs.multipleTable.toggleRowSelection(menu, isSelect);
            if(menu.children && menu.children.length > 0){
                this.selectChil(isSelect,menu.children);
            }
        }
    },

    //选中/取消当前元素的父元素
    selectParent(row, selection){
        if(row.menuParent == 0){
            //没有父元素
            return;
        }
        var isSelect = this.isSelectCurrentRow(row, selection);
        // console.log(1111,isSelect, row)
        this.selectParentCh(isSelect, this.tableData, selection, row)
    },
    selectParentCh(isSelect, menuList, selection, row){
        for (let index = 0; index < menuList.length; index++) {
            var menu = menuList[index];
            if(menu.menuId == row.menuParent){
                if(isSelect){
                    selection.push(menu)
                }else{
                    //查看是否有选中同级兄弟元素
                    if(this.isSelectOne(menu.children, selection)){
                        return;
                    }
                    for(var i = 0;i<selection.length; i++){
                        if(row.menuParent == selection[i].menuId){
                            selection.splice(i,1);
                            break;
                        }
                    }
                }
                this.$refs.multipleTable.toggleRowSelection(menu, isSelect);

                this.selectParent(menu, selection);
                break;
            }
            if(menu.children && menu.children.length > 0){
                this.selectParentCh(isSelect, menu.children, selection, row)
            }
        }
    },

    /**
     * 查找当前元素的父元素
     */
    findAllParent: function(row, selection) {
        if(row.menuParent == 0){
            return undefined;
        }
      var isChild = true;
      for (let index = 0; index < this.tableData.length && isChild; index++) {
        const element = this.tableData[index];

        for (let index = 0; index < element.children.length; index++) {
          const child = element.children[index];

          if (child.roleMenuId == row.roleMenuId) {
            isChild = false;
            return element;
          }
        }
      }
    },
    /**
     * 判断当前行是否选中
     */
    isSelectCurrentRow: function(row, selection) {
      for (let index = 0; index < selection.length; index++) {
        const element = selection[index];
        if (row.menuId == element.menuId) {
          return true;
        }
      }
      return false;
    },
    /**
     * 检查数组中的行是否存在选中的数据
     */
    isSelectOne: function(rows, selection) {
      for (let index = 0; index < rows.length; index++) {
        const element = rows[index];

        if (this.isSelectCurrentRow(element, selection)) {
          return true;
        }
      }
      return false;
    },
    /**
     * 关闭窗口
     */
    closeHandler: function() {
      this.$refs.multipleTable.clearSelection();
      this.$emit("close");
    },
    /**
     * 保存
     */
    saveHandler: function() {
      this.loading = true;
      var selected = this.$refs.multipleTable.selection;
      this.axios
        .post(replaceUrlParam(adminMenusSave,[this.userId]) , selected)
        .then(response => {
          if (response.data.status == "SUCCESS") {
            this.closeHandler();
            this.$message.success("权限添加成功");
          } else {
            this.$message.error("权限添加失败");
          }
          this.loading = false;
        })
        .catch(response => {
          this.$message.error("权限添加失败");
          this.loading = false;
        });
    },
    /**
     * 数据加载完成后根据选择状态更新授权列表选择项
     */
    openHandler: function() {
      let that = this;
      setTimeout(function() {
        that.setSelected(that.tableData);
      }, 1000);
    },
    setSelected: function(array) {
      array.forEach(row => {
        if (row.selected == true) {
          this.$refs.multipleTable.toggleRowSelection(row, true);

          if (row.hasChildren) {
            this.setSelected(row.children);
          }
        }
      });
      this.loading = false;
    }
  }
};
</script>
<style scoped>
</style>